﻿
#
# Author : itech
# 

import re
import ldap
from GlobalLogging import GlobalLogging

# ====================================================
# LDAP search

UserType_alias = 'alias'
UserType_fullname = 'fullname'
UserType_email = 'email'

def findUserType(user):
  user = user.strip()
  if not user.find('@') == -1: 
    return UserType_email
  elif user.find(' ') == -1 and user.find('-') == -1 and user.find('(') == -1 :
    return UserType_alias
  else:
    return UserType_fullname

def constructSearchFilter(userType, user):   
  SearchFilter = ''
  if userType == UserType_alias:
    searchFilter = str.format("sAMAccountName=%s" % user)
  elif userType == UserType_email:
    searchFilter = str.format("mail=%s" % user)
  elif userType == UserType_fullname:
    user = user.replace('(','\(')
    user = user.replace(')', '\)')
    searchFilter = str.format("displayName=%s" % user)
  else:
    pass
  return searchFilter
    
def searchLDAP(ldapuser,ldappass,ldappath,baseDN,searchFilter,trynum = 5):
    i = 0 
    result_data = None
    while(1):
        try:
            l = ldap.initialize(ldappath)
            l.protocol_version = ldap.VERSION3
            l.simple_bind(ldapuser, ldappass)
            
            searchScope = ldap.SCOPE_SUBTREE
            retrieveAttributes = None 

            ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
            while 1:
              result_type, result_data = l.result(ldap_result_id, 0,timeout=60)
              if result_type == ldap.RES_SEARCH_ENTRY:
                GlobalLogging.getInstance().debug(repr(result_data))
                break

        except ldap.LDAPError, e:
            pass
     
        if(not result_data == None or i > trynum): break
        i+=1
        GlobalLogging.getInstance().debug("try to search LDAP server : " + str(i))
        
    if result_data == None:
       GlobalLogging.getInstance().error('LDAP server is busy, please try again later')
       
    return result_data
    
def parseUserInfoFromLDAP(result_data):
    if result_data == None:
      return None, None, None

    regrex = "'sAMAccountName': \['(.*?)'\].*'mail': \['(.*?)'\].*'displayName': \['(.*?)'\]"
    mobj = re.search(regrex,repr(result_data))
    if not mobj == None :
        alias = mobj.groups()[0]
        email = mobj.groups()[1]
        fullname = mobj.groups()[2]
        return alias, email, fullname
    else:
        GlobalLogging.getInstance().error('Cannot match detail information')
        GlobalLogging.getInstance().debug(repr(result_data))
        return None, None, None
        
def UserExistInLDAPOrNot(ldapuser,ldappass,ldappath,ldapbasedn,user):
    usertype = UserType_alias
    filter = LDAP.constructSearchFilter(usertype,user)
    resultdata = LDAP.searchLDAP(ldapuser,ldappass,ldappath,ldapbasedn,filter)
    if result_data == None: 
      return True
    else:
      return False